package com.qf.usermanageradmin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.usermanageradmin.entity.LoginUser;
import com.qf.usermanageradmin.entity.PageVO;
import com.qf.usermanageradmin.entity.User;
import com.qf.usermanageradmin.entity.UserDTO;
import com.qf.usermanageradmin.service.LoginService;
import com.qf.usermanageradmin.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/user")
//@CrossOrigin
//@CrossOrigin(origins={"http://localhost:8081"},allowCredentials="true")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;


    @PostMapping("/login")
    public R login(@RequestBody LoginUser loginUser, HttpSession session){
        User user = loginService.login(loginUser);
        session.setAttribute("user", user);
        return R.ok(user);
    }

    // 登出
    @GetMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.ok();
    }

    // 查询全部用户信息 V1 无参
    // 查询全部用户信息 V2 分页
    // 查询全部用户信息 V3 分页加模糊搜索
    @GetMapping("/list")
    public R list(UserDTO userDTO){
        PageHelper.startPage(userDTO.getPageNum(), userDTO.getPageSize());

        List<User> list = loginService.list(userDTO);
        if (list == null || list.size() == 0){
            return R.error("没有用户信息");
        }
        PageInfo<User> pageInfo = new PageInfo<>(list);
        PageVO pageVO = new PageVO();
        pageVO.setList(pageInfo.getList());
        pageVO.setPageNum(pageInfo.getPageNum());
        pageVO.setPageSize(pageInfo.getPageSize());
        pageVO.setTotal(pageInfo.getTotal());
        pageVO.setPages(pageInfo.getPages());
        return R.ok(pageVO);
    }

    // 批量删除
    @GetMapping("/del/batch")
    public R batchDelete(@RequestParam List<Integer> ids){
        if (ids == null || ids.size() == 0){
            return R.error("请选择要删除的用户");
        }
        int count = loginService.batchDelete(ids);
        if (count == 0){
            return R.error("删除失败");
        }
        return R.ok(count);
    }

    // 添加用户
    @PostMapping("/add")
    public R add(@RequestBody User user){
        int count = loginService.add(user);
        if (count == 0){
            return R.error("添加失败");
        }
        return R.ok(count);
    }

    // 修改用户
    @PostMapping("/edit")
    public R edit(@RequestBody User user) {
        log.debug("更新用户:{}", user);
        int count = loginService.editById(user);
        if (count == 0) {
            return R.error("更新失败");
        }
        return R.ok(count);
    }
}
